# 导入必要的库和模块
import gradio as gr
import pickle
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
from PIL import Image

# 加载保存的KNN模型
try:
    with open('best_knn.pkl', 'rb') as file:
        knn = pickle.load(file)
except FileNotFoundError:
    print("无法找到保存的KNN模型文件")
    exit()
except Exception as e:
    print("加载KNN模型时出现错误:", str(e))
    exit()

# 定义预处理函数
def preprocess(image):
    image = Image.fromarray(image)  # 将数组转换为图像对象
    image = image.resize((8, 8)).convert('L')  # 调整图像大小并转换为灰度图像
    image_array = np.array(image)  # 将图像转换为numpy数组
    flattened_image = image_array.ravel()  # 将图像数组展平为一维数组
    return flattened_image

# 定义预测函数
def predict(image):
    preprocessed_image = preprocess(image)  # 预处理输入的图像
    predicted_digit = knn.predict([preprocessed_image])[0]  # 使用KNN模型进行预测
    return str(predicted_digit) 

# 创建Gradio接口
iface = gr.Interface(fn=predict, inputs='sketchpad', outputs='label')

# 启动Gradio接口
iface.launch()
